/*--------------------------------------------------------------------------------------*\
**
** adv_ferry.cpp
**
** Heroes IV
** Copyright 2000, The 3DO Company
**
\*--------------------------------------------------------------------------------------*/

// kill the 255+ character identifier warning.  Templates tend to exceed that easily.
#include "precompiled.h"
#pragma warning( disable: 4786 )

#include "adventure_events_playback.h"

#include "adventure_frame.h"
#include "adventure_map.h"
#include "adventure_map_window.h"

t_adventure_event_playback::t_adventure_event_playback ( t_adventure_event_list const &	events_list ) 
: m_events_list ( events_list ) , t_idle_processor(1) 
{ 
}

void t_adventure_event_playback::attach( t_adventure_map *  map )
{ 
	m_map = map; 
}

void t_adventure_event_playback::start()
{
	if (m_map == NULL) 
		return;

	m_current_event			= m_events_list.begin();

	if (m_current_event != m_events_list.end())
		m_current_event->get()->execute_event( m_map , m_map->get_event_header());

	resume_idle_processing(); 
}

void t_adventure_event_playback::stop()
{
	if ( m_current_event != m_events_list.end() && m_current_event._Mynode() != NULL )
		m_current_event->get()->cancel_event();

	m_current_event = m_events_list.end();

	suspend_idle_processing();
}

void t_adventure_event_playback::set_player_turn ( int player_turn )
{ 
	m_player_turn = player_turn;
}

void t_adventure_event_playback::on_idle()
{
	if (m_current_event ==  m_events_list.end())
	{
		m_map->event_playback_finish();

		return;
	}

	m_current_event->get()->update();

	return; 
}

// ----------------------------------------------------
// adventure_event_finished : this function has to be called by every adventure object when it finishes
//  otherwise it will stall the event playback.
// ----------------------------------------------------
void t_adventure_event_playback::adventure_event_finished( t_adventure_event_base * event)
{
	if (event == NULL) 
		return;

	//check if we recived the current events finish call
	if (m_current_event->get() != event)
		return;

	m_current_event++;

	//the reason for bounding the execute_event function within suspend and resume idle precoessors
	//calls is because some events can run_modal which then would result in 2 calls to the on_idle of 
	//the playback object.

	if (m_current_event !=  m_events_list.end())
	{
		suspend_idle_processing();

		m_current_event->get()->execute_event( m_map , m_map->get_event_header());
	
		resume_idle_processing(); 
	}
	else
		m_map->event_playback_finish();
}

